package exttable.login;

import dbutils.DbUtils;
import exttable.formgenerator.MessageFactory;
import exttable.formgenerator.StaticMethods;
import options.AppSettings;
import utils.Localisation;

import javax.swing.*;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by IntelliJ IDEA.
 * User: Admin
 * Date: Feb 4, 2010
 * Time: 12:58:33 AM
 * To change this template use File | Settings | File Templates.
 */
public class PasswordChecker {

    public static boolean check(String login, String password, String ip) {
        try {
            String sysPass = "";
            Connection c = DbUtils.getDBConnectionGeneral();
            PreparedStatement ps = c.prepareStatement(" select pass, in_system, access_denied, computer_name, amount_access_failures from login where login = ?");
            ps.setString(1, login);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                if(rs.getInt("in_system")==1 & !rs.getString("computer_name").equals(System.getenv("COMPUTERNAME"))){
                    c.close();
                    MessageFactory.getMessage(Localisation.getMessage("inSystem"));
                    return  false;
                }
                else if(rs.getInt("access_denied")==1){
                    c.close();
                    MessageFactory.getMessage(Localisation.getMessage("accessDenied"));
                    System.exit(0);
//                    return  false;
                }
                sysPass = rs.getString(1);
                if(AppSettings.get("generalSettings","lockUserAfterFailedLoginAttempts","").equals("true")){
                    checkAmountAccessFailures(login, password, sysPass, c, rs);
                }
            }


            c.close();
            if(sysPass.equals(getHash(password))){
                StaticMethods.changeAmountAccessFailures(0, login);
            }
            return sysPass.equals(getHash(password));
        }
        catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private static String getHash(String pas) {
        String toReturn;
        try {
            MessageDigest m = MessageDigest.getInstance("MD5");
            m.update(pas.getBytes(), 0, pas.length());
            toReturn = new BigInteger(1, m.digest()).toString(16);
        }
        catch (NoSuchAlgorithmException ex) {
            toReturn = "";
        }
        return toReturn;
    }

    private static void checkAmountAccessFailures(String login, String password, String sysPass,  Connection c, ResultSet rs) throws SQLException {
        if (rs != null){
            Integer amountAccessFailures= Integer.valueOf(AppSettings.get("generalSettings", "amountAccessFailures", "").toString());
            if(rs.getInt("amount_access_failures")==amountAccessFailures.intValue()){
                c.close();
                JOptionPane.showMessageDialog(null, Localisation.getMessage("amountAccessFailures"), Localisation.getMessage("error.title"), JOptionPane.WARNING_MESSAGE);
                System.exit(0);
            }else {
                rs.beforeFirst();
                rs.last();
                int size = rs.getRow();
                if(size>0 & !sysPass.equals(getHash(password))){
                    int amount=rs.getInt("amount_access_failures");
                    amount++;
                    StaticMethods.changeAmountAccessFailures(amount, login);
                }
            }

        }
    }

}
